<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="日志类型">
              <el-select v-model="searchForm.logType" placeholder="全部" clearable>
                <el-option label="事件日志" value="event" />
                <el-option label="普通日志" value="normal" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="全部" clearable>
                <el-option label="进行中" value="processing" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keyword" placeholder="请输入关键词搜索" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 日志列表区域 - 使用el-row布局 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card>
          <el-button type="primary" @click="showCreateLogDialog">
            <el-icon>
              <Plus />
            </el-icon>
            新建日志
          </el-button>
          <div v-for="log in filteredLogs" :key="log.id" :span="24" class="log-item-col mt-2">
            <el-card class="log-item" shadow="hover">
              <div class="log-header">
                <div class="log-title">
                  <el-tag :type="log.type === 'event' ? 'danger' : ''" size="small">
                    {{ log.type === 'event' ? '事件' : '普通' }}
                  </el-tag>
                  <el-tag v-if="log.status === 'processing'" type="warning" size="small">
                    进行中
                  </el-tag>
                  <el-tag v-else type="success" size="small">已完成</el-tag>
                </div>
                <div class="log-time">{{ log.time }}</div>
              </div>
              <div class="title-text">{{ log.title }}</div>

              <div class="log-content">
                <p>{{ log.content }}</p>
                <div v-if="log.location" class="log-location">
                  <el-icon>
                    <Location />
                  </el-icon>
                  {{ log.location }}
                </div>
              </div>

              <div class="log-actions">
                <el-button type="text" @click="showLogDetail(log)">
                  <el-icon>
                    <View />
                  </el-icon>
                  查看详情
                </el-button>
                <el-button type="text" @click="showAddToSolutionDialog(log)">
                  <el-icon>
                    <FolderAdd />
                  </el-icon>
                  添加到方案
                </el-button>
                <el-button type="text" @click="deleteLog(log.id)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card style="height: 100%;">


        </el-card>
      </el-col>
    </el-row>

    <!-- 新建日志对话框 -->
    <el-dialog v-model="logDialog.visible" :title="`新建${logDialog.type === 'event' ? '事件' : '普通'}日志`" width="50%">
      <el-form :model="logForm" label-width="100px">
        <el-form-item label="日志类型">
          <el-radio-group v-model="logDialog.type">
            <el-radio-button label="event">事件日志</el-radio-button>
            <el-radio-button label="normal">普通日志</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="标题" required>
          <el-input v-model="logForm.title" placeholder="请输入日志标题" />
        </el-form-item>

        <el-form-item v-if="logDialog.type === 'event'" label="地点">
          <el-input v-model="logForm.location" placeholder="请在地图上选择地点">
            <template #append>
              <el-button @click="selectLocationOnMap">选择</el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="时间" required>
          <el-date-picker v-model="logForm.time" type="datetime" placeholder="选择时间"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <el-form-item v-if="logDialog.type === 'event'" label="处理过程">
          <div class="process-steps">
            <div v-for="(step, index) in logForm.processSteps" :key="index" class="process-step">
              <el-input v-model="step.content" :placeholder="`步骤${index + 1}内容`"
                style="width: 80%; margin-right: 10px;" />
              <el-time-picker v-model="step.time" placeholder="时间" value-format="HH:mm" style="width: 18%;" />
              <el-button v-if="index > 0" type="danger" text @click="removeProcessStep(index)">
                删除
              </el-button>
            </div>
            <el-button type="primary" text @click="addProcessStep">
              <el-icon>
                <Plus />
              </el-icon>
              添加处理步骤
            </el-button>
          </div>
        </el-form-item>

        <el-form-item v-if="logDialog.type === 'event'" label="结束时间">
          <el-date-picker v-model="logForm.endTime" type="datetime" placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <el-form-item label="内容" required>
          <el-input v-model="logForm.content" type="textarea" :rows="4" placeholder="请输入日志内容" />
        </el-form-item>

        <el-form-item label="附件">
          <el-upload v-model:file-list="logForm.attachments" action="#" multiple :auto-upload="false">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="logDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveLog">确定</el-button>
      </template>
    </el-dialog>

    <!-- 日志详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="detailDialog.data.title" width="60%">
      <div class="log-detail">
        <div class="log-meta">
          <span>{{ detailDialog.data.time }}</span>
          <span v-if="detailDialog.data.location">
            <el-icon>
              <Location />
            </el-icon>
            {{ detailDialog.data.location }}
          </span>
        </div>

        <div v-if="detailDialog.data.type === 'event'" class="process-section">
          <h4>事件处理过程</h4>
          <el-timeline>
            <el-timeline-item v-for="(step, index) in detailDialog.data.processSteps" :key="index"
              :timestamp="step.time">
              {{ step.content }}
            </el-timeline-item>
          </el-timeline>
        </div>

        <div class="summary-section">
          <h4>{{ detailDialog.data.type === 'event' ? '事件总结' : '日志内容' }}</h4>
          <p>{{ detailDialog.data.content }}</p>
          <div v-if="detailDialog.data.endTime" class="end-time">
            结束时间：{{ detailDialog.data.endTime }}
          </div>
        </div>

        <div v-if="detailDialog.data.attachments?.length" class="attachment-section">
          <h4>附件</h4>
          <ul>
            <li v-for="(file, index) in detailDialog.data.attachments" :key="index">
              {{ file.name }}
              <el-button type="text" @click="downloadAttachment(file)">下载</el-button>
            </li>
          </ul>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="showAddToSolutionDialog(detailDialog.data)">
          添加到方案库
        </el-button>
        <el-button @click="printLog">打印</el-button>
      </template>
    </el-dialog>

    <!-- 添加到方案库对话框 -->
    <el-dialog v-model="solutionDialog.visible" title="添加到方案库" width="50%">
      <el-form :model="solutionForm" label-width="100px">
        <el-form-item label="方案名称" required>
          <el-input v-model="solutionForm.name" placeholder="请输入方案名称" />
        </el-form-item>

        <el-form-item v-if="solutionDialog.data.type === 'event'" label="选择步骤">
          <el-checkbox-group v-model="solutionForm.selectedSteps">
            <el-checkbox v-for="(step, index) in solutionDialog.data.processSteps" :key="index"
              :label="`步骤${index + 1}`">
              步骤{{ index + 1 }}: {{ step.content }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="标签">
          <el-select v-model="solutionForm.tags" multiple filterable allow-create placeholder="请选择或输入标签">
            <el-option v-for="tag in commonTags" :key="tag" :label="tag" :value="tag" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="solutionForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="solutionDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveToSolutionLibrary">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import {
  Plus,
  Location,
  View,
  FolderAdd,
  Delete
} from '@element-plus/icons-vue';

// 日志数据
const logs = ref([
  {
    id: 1,
    title: '朝阳区供水管道破裂抢修',
    type: 'event',
    time: '2023/05/15 09:30',
    location: '朝阳区建国路与东三环交叉口',
    content: '朝阳区建国路与东三环交叉口处供水管道出现破裂，影响周边5个小区供水',
    status: 'completed',
    processSteps: [
      { time: '09:30', content: '接到居民投诉，立即派维修人员前往现场查看' },
      { time: '10:15', content: '确认管道破裂位置，关闭相关阀门，开始抢修' },
      { time: '13:45', content: '完成管道更换，开始恢复供水' }
    ],
    endTime: '2023/05/15 14:00',
    content: '经过4个半小时抢修，完成管道更换，恢复供水。共影响用户的约500户，抢修期间启用应急供水车保障居民用水。',
    attachments: [
      { name: '现场照片.jpg', url: '#' },
      { name: '维修记录.pdf', url: '#' }
    ]
  },
  {
    id: 2,
    title: '海淀区水压异常排查',
    type: 'event',
    time: '2023/05/10 14:20',
    location: '海淀区中关村',
    content: '海淀区中关村区域多个用户反映水压偏低，需排查原因',
    status: 'completed',
    processSteps: [
      { time: '14:20', content: '接到用户水压异常反馈' },
      { time: '15:00', content: '现场检查供水管网压力' },
      { time: '16:30', content: '发现水泵故障，进行维修' }
    ],
    endTime: '2023/05/10 17:00',
    content: '排查发现3号水泵故障，更换后水压恢复正常。',
    attachments: []
  },
  {
    id: 3,
    title: '月度管网巡检报告',
    type: 'normal',
    time: '2023/05/05 10:00',
    content: '完成5月份供水管网例行巡检，共检查管线120公里，发现3处轻微渗漏，已安排维修。主要问题集中在老旧小区...',
    status: 'completed',
    attachments: []
  },
  {
    id: 4,
    title: '西城区供水管道改造',
    type: 'event',
    time: '2023/04/28 14:00',
    location: '西城区',
    content: '西城区老旧供水管道改造工程启动',
    status: 'processing',
    processSteps: [
      { time: '14:00', content: '工程启动会议' },
      { time: '15:30', content: '现场施工准备' }
    ],
    content: '西城区老旧供水管道改造工程已启动，预计工期30天。',
    attachments: []
  },
  {
    id: 5,
    title: '新员工培训记录',
    type: 'normal',
    time: '2023/04/28 14:00',
    content: '对新入职的9名调度员进行系统培训，内容包括管网结构、调度流程、应急处理等。培训时长8小时，考核通过率100%。',
    status: 'completed',
    attachments: []
  }
]);

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  logType: '',
  status: '',
  keyword: ''
});

// 过滤后的日志列表
const filteredLogs = computed(() => {
  let result = logs.value;

  // 按日期范围筛选
  if (searchForm.dateRange?.length === 2) {
    const [start, end] = searchForm.dateRange;
    result = result.filter(log => {
      const logDate = log.time.split(' ')[0].replace(/\//g, '-');
      return logDate >= start && logDate <= end;
    });
  }

  // 按日志类型筛选
  if (searchForm.logType) {
    result = result.filter(log => log.type === searchForm.logType);
  }

  // 按状态筛选
  if (searchForm.status) {
    result = result.filter(log => log.status === searchForm.status);
  }

  // 按关键词筛选
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase();
    result = result.filter(log =>
      log.title.toLowerCase().includes(keyword) ||
      log.content.toLowerCase().includes(keyword)
    );
  }

  return result;
});

// 日志对话框
const logDialog = reactive({
  visible: false,
  type: 'event' // 'event' or 'normal'
});

const logForm = reactive({
  title: '',
  location: '',
  time: '',
  content: '',
  processSteps: [
    { time: '', content: '' }
  ],
  endTime: '',
  attachments: []
});

// 显示新建日志对话框
const showCreateLogDialog = () => {
  logDialog.visible = true;
  logDialog.type = 'event';

  // 重置表单
  Object.assign(logForm, {
    title: '',
    location: '',
    time: '',
    content: '',
    processSteps: [
      { time: '', content: '' }
    ],
    endTime: '',
    attachments: []
  });
};

// 添加处理步骤
const addProcessStep = () => {
  logForm.processSteps.push({ time: '', content: '' });
};

// 删除处理步骤
const removeProcessStep = (index) => {
  logForm.processSteps.splice(index, 1);
};

// 保存日志
const saveLog = () => {
  // 验证表单
  if (!logForm.title || !logForm.time || !logForm.content) {
    ElMessage.warning('请填写必填项');
    return;
  }

  if (logDialog.type === 'event' && logForm.processSteps.some(step => !step.time || !step.content)) {
    ElMessage.warning('请填写完整的处理步骤');
    return;
  }

  // 创建新日志
  const newLog = {
    id: logs.value.length + 1,
    title: logForm.title,
    type: logDialog.type,
    time: logForm.time,
    location: logForm.location,
    content: logForm.content,
    status: logDialog.type === 'event' && !logForm.endTime ? 'processing' : 'completed',
    processSteps: [...logForm.processSteps],
    endTime: logForm.endTime,
    attachments: [...logForm.attachments]
  };

  logs.value.unshift(newLog);
  logDialog.visible = false;
  ElMessage.success('日志保存成功');
};

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: {}
});

// 显示日志详情
const showLogDetail = (log) => {
  detailDialog.visible = true;
  detailDialog.data = { ...log };
};

// 打印日志
const printLog = () => {
  window.print();
};

// 下载附件
const downloadAttachment = (file) => {
  ElMessage.info(`开始下载: ${file.name}`);
  // 实际项目中这里应该是调用下载API
};

// 删除日志
const deleteLog = (id) => {
  ElMessageBox.confirm('确定要删除这条日志吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    logs.value = logs.value.filter(log => log.id !== id);
    ElMessage.success('删除成功');
  }).catch(() => {
    // 取消删除
  });
};

// 方案库对话框
const solutionDialog = reactive({
  visible: false,
  data: {}
});

const commonTags = ref([
  '管道维修',
  '水压异常',
  '设备故障',
  '用户投诉',
  '计划施工'
]);

const solutionForm = reactive({
  name: '',
  selectedSteps: [],
  tags: [],
  remark: ''
});

// 显示添加到方案库对话框
const showAddToSolutionDialog = (log) => {
  solutionDialog.visible = true;
  solutionDialog.data = { ...log };

  // 初始化表单
  Object.assign(solutionForm, {
    name: log.title + '处理方案',
    selectedSteps: log.processSteps?.map((_, index) => `步骤${index + 1}`) || [],
    tags: [],
    remark: ''
  });
};

// 保存到方案库
const saveToSolutionLibrary = () => {
  if (!solutionForm.name) {
    ElMessage.warning('请输入方案名称');
    return;
  }

  // 这里应该是调用API保存到方案库
  ElMessage.success('方案已保存到方案库');
  solutionDialog.visible = false;
};

// 在地图上选择地点
const selectLocationOnMap = () => {
  ElMessage.info('打开地图选择位置');
  // 实际项目中这里应该集成地图组件
};

// 搜索
const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
};
</script>

<style scoped>

.search-card :deep(.el-form-item) {
    margin-bottom: 0px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.log-list-card {
  margin-bottom: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.total-count {
  font-size: 14px;
  color: #909399;
}

.log-list {
  margin-top: 20px;
}

.log-item-col {
  margin-bottom: 20px;
}

.log-item {
  margin-bottom: 10px;
  transition: all 0.3s;
}

.log-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.log-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-text {
  font-weight: bold;
  font-size: 16px;
}

.log-time {
  color: #909399;
  font-size: 14px;
}

.log-content {
  margin: 10px 0;
  color: #606266;
}

.log-content p {
  margin: 0;
  line-height: 1.6;
}

.log-location {
  margin-top: 8px;
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.log-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.process-steps {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.process-step {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.log-detail {
  padding: 10px;
}

.log-meta {
  margin: 10px 0;
  color: #909399;
  display: flex;
  gap: 20px;
}

.process-section,
.summary-section,
.attachment-section {
  margin-bottom: 20px;
}

.summary-section p {
  line-height: 1.8;
}

.end-time {
  margin-top: 10px;
  font-style: italic;
  color: #909399;
}

.attachment-section ul {
  list-style: none;
  padding: 0;
}

.attachment-section li {
  padding: 5px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}
</style>